﻿using System;
using System.Linq;
using System.Net.WebSockets;
using Newtonsoft.Json;
using ZilLion.Service.Core.Log;
using ZilLion.Service.Core.WebSocket;
using ZilLion.Service.Core.WebSocket.Interface;
using ZilLion.Service.TaskPlatform.Domain.Entity;

namespace ZilLion.Service.TaskPlatform.Controllers.Websocket
{
    /// <summary>
    ///     运行日志转发
    /// </summary>
    public class TaskClientLogMessageHandleStrategy : IMessageHandleStrategy
    {
        public async void HandleMessage(SocketMessage message, WebSocket socket, IWebSocketHandler messageHandle)
        {
            var id = messageHandle.WebSocketConnectionManager.GetId(socket);
            var clientkey = messageHandle.WebSocketConnectionManager.GetGroupByWebSocketId(id);
            var clientNo = JsonConvert.DeserializeObject<SocketKeyDto>(clientkey).ClientNo;
            var workstation = new SocketKeyDto
            {
                ClientNo = clientNo,
                ClientType = "Workstation"
            };
            var targetids =
                messageHandle.WebSocketConnectionManager.GetAllFromGroup(JsonConvert.SerializeObject(workstation)).ToList();

            foreach (var targetid in targetids)
            {
                var targetSocket = messageHandle.WebSocketConnectionManager.GetSocketById(targetid);
                if (targetSocket != null && targetSocket.State == WebSocketState.Open)
                    try
                    {
                        await messageHandle.SendMessageAsync(targetSocket, message);
                    }
                    catch (Exception e)
                    {
                        ZilLionLogManager.Instance().Error(e);
                    }
            }
        }
    }
}